'''
  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.
'''
from network import WLAN, STA_IF
from conf import wifi
import asyncio,machine
from swe.log import log
from time import sleep

def connect():
    wlan = WLAN(STA_IF)
    wlan.active(True)
    wlan.connect(wifi.ssid, wifi.password)
    
'''
isconnected 方法无法确保在线，可能dhcp未完成，特此新增一个符合生活习惯的函数
'''

def is_online():
    import requests
    try:
        if requests.get("https://www.baidu.com/").status_code == 200:
            log("debug", "Sys::Setup::network", "Internet connection set up successfully.", if_print = False)
            return True
    except Exception as error:
        log("error", "Sys::Setup::network", "I'm still offline!", if_print = False)
        return False
    
def wait():
    t = 0
    while not WLAN(STA_IF).isconnected:
        sleep(1)
        t += 1
        if t >= wifi.connectTimeLimit:
            log("fatal", "Sys::Setup::network", "Wifi connect time limited, used " + str(t) + "s.", True)
            sleep(3)#留出时间观察repl
            machine.reset()
    log("debug", "Sys::Setup::network", "Wifi connected, used " + str(t) + "s.", False)
    while not is_online():
        sleep(1)
        t += 1
        if t >= (wifi.connectTimeLimit + wifi.getOnLineTimeLimit):
            log("fatal", "Sys::Setup::network", "I have been offline for " + str(t) + "s, out of time! Now reboot!", True)
            sleep(3)
            machine.reset()
    log("debug", "Sys::Setup::network", "Wifi connected completely!", if_print = False)